package modes

import (
	"fmt"
)

/*
 * 描述: 班型表
 *
 * Status 状态  0 启用  1 禁用
 * UpgRade 0不升级 1升级
 *****************************/

type SClass struct {
	Id        int64  `json:"c_id" xorm:"id"`               //班型ID
	PId       int64  `json:"c_pid" xorm:"pid"`             //项目ID
	Name      string `json:"c_name" xorm:"name"`           //班型名称
	Price     int64  `json:"c_price" xorm:"price"`         //班型价格
	Status    int    `json:"c_status" xorm:"status"`       //状态
	At        int64  `json:"c_at" xorm:"at"`               //时间
	Start     int64  `json:"c_start" xorm:"start"`         //报班时间
	End       int64  `json:"c_end" xorm:"end"`             //结束时间
	Coun      int64  `json:"c_coun" xorm:"coun"`           //当前报名学员
	ThisId    int64  `json:"c_thisid" xorm:"this_id"`      //当前续费ID
	UpgRade   int    `json:"c_upgrade" xorm:"upgrade"`     //是否升级版
	ClassUrl  string `json:"c_class_url" xorm:"class_url"` //班型详情链接
	ISShow    int64  `json:"c_is_show" xorm:"is_show"`     //是否在APP展示
	ValidTerm int    `json:"valid_term" xorm:"valid_term"` // 班型有效期(后端存储单位:月)

}

func (this *SClass) TableName() string {
	return "class"
}

func (this *SClass) Get() (bool, error) {
	return Db(0).Get(this)
}

func (this *SClass) StudenCount(id, coun int) error {
	sql := fmt.Sprintf("UPLOAD class SET coun = coun + %d WHERE id = %d", coun, id)
	_, err := Db(0).Exec(sql)
	return err
}

func (this *SClass) where(fage, count, page int, where, field string) ([]SClass, error) {
	list := make([]SClass, 0)
	var err error
	page--
	if 0 == fage { // 从小到大排序
		err = Db(0).Where(where).
			Asc(field).
			Limit(count, page*count).
			Find(&list)
	} else { // 从大到小排序
		err = Db(0).Where(where).
			Desc(field).
			Limit(count, page*count).
			Find(&list)
	}
	return list, err
}

type ClassData struct {
	SClass  `json:"class" xorm:"extends"`
	Project `json:"pro" xorm:"extends"`
}

func (this *ClassData) Lookups(val *Pager) error {
	list := make([]ClassData, 0)
	val.TName = "class"
	val.Page--
	var field, sort string
	switch val.Coll {
	case 0:
		field = fmt.Sprintf("%s.at", val.TName) //时间排序
	case 1:
		field = fmt.Sprintf("%s.pid", val.TName) // 项目
	default:
		field = fmt.Sprintf("%s.at", val.TName) // 时间排序
	}
	if 1 == val.Rules {
		sort = fmt.Sprintf("%s asc", field)
	} else {
		sort = fmt.Sprintf("%s desc", field)
	}
	val.Total, _ = Db(0).Table(val.TName).Where(val.ToWhere()).Count(this)
	err := Db(0).Table(val.TName).
		Join("INNER", "project", fmt.Sprintf("%s.pid = project.id", val.TName)).
		Where(val.ToWhere()).
		OrderBy(sort).
		Limit(val.Count, val.Page*val.Count).
		Find(&list)
	if err == nil {
		val.List = list
	}
	return err
}
